const WebSocket = require('ws')
const ws = new WebSocket.Server({ port: 9528 })

// let clients = {}
// let clientName = 0

// ws.on('connection', (client) => {

//   client.name = ++clientName
//   clients[client.name] = client

//   client.on('message', (msg) => {
//     broadcast(client, msg)
//   })

//   client.on('close', () => {
//     delete clients[client.name]  
//     console.log(client.name + ' 离开了~')
//   })
// })

// function broadcast(client, msg) {
//   for (var key in clients) {
//     clients[key].send(client.name + ' 说：' + msg)
//   }
// }

const wss=new WebSocket.Server({port:9527})

wss.on('connection',function connection(ws){

  ws.on('open',function open(){
    console.log('connected');
    ws.send('hello')
  })

  ws.on('message',function incoming(data){
    // ws.send(data)

    wss.clients.forEach(function each(client){
      if(client.readyState===WebSocket.OPEN){
        client.send(data)
      }
    })
  })
  
  ws.on('close',function close(){
    console.log('disconnected');
  })
})